<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/component/commonTagLib.jsp" %>

<!DOCTYPE html>
<html>
<head>
    <title><spring:message code="message.basic"></spring:message></title>
    <%@ include file="/WEB-INF/component/commonCSS.jsp" %>
</head>
<body class="skin-blue-light sidebar-mini fixed skin-blue-light-frame">
    <section class="content-header">
        <h1><spring:message code="message.title.center_ziyonghu"></spring:message></h1>
        <ol class="breadcrumb">
            <li><a href="${ctx}/home.jsp"><i class="fa fa-home"></i><spring:message code="message.lable.first"></spring:message></a></li>
             <li class="active"><a href="#"><spring:message code="message.title.xiTongSheZhi" /></a></li>
             <li class="active"><a href="#"><spring:message code="message.title.yongHuGuanLi" /></a></li>
            <li class="active"><a href="#"><spring:message code="message.title.center_ziyonghu"></spring:message></a></li>
        </ol>
    </section>
    <section class="content">
        <div class=" box box-success">
            <div class="box-body">
                    <div class="input">
                    <div class="textalign1"><spring:message code="message.lable.username"></spring:message><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="searchName" placeholder="<spring:message code="message.lable.username" />" maxlength="50" />
                    </div>
                    <div class="textalign1"><spring:message code="message.lable.userzhanghao" /><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="subUsername"  placeholder="<spring:message code="message.lable.userzhanghao" />" maxlength="25" />
                    </div>
           			
                    <div class="textalign1"><spring:message code="message.lable.status"/><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                       <select id="status" class="textinput">
                           	<option value="" ><spring:message code="message.select.option"/></option>
                            <option value="1" ><spring:message code="message.button.start"/></option>
                            <option value="0" ><spring:message code="message.button.stop"/></option>
                           </select>
                     </div>
                     <div class="textalign1" >
                   <ms:btn url="/sysUser/getSubUserList.html"><button type="button" class="btn btn-success btn-sm" onclick="search();"><spring:message code="message.button.seachSpacing"></spring:message></button></ms:btn> 
                </div>
            </div>
            </div>
        </div>
        <table class="jqgrid" id="gridlist"></table>
        <div id="gridpage"></div>
        <div class=" box box-warning bottongroup">
             <ms:btn url="/sysUser/subSaveUser.html"><a href="javascript:showDiv('add');" class="btn btn-primary btn-sm"><spring:message code="message.button.addSpacing"></spring:message></a></ms:btn>
             <ms:btn url="/sysUser/subEnable.html"><label class="btn btn-primary btn-sm" onclick="batchChangeStatus(1)"><spring:message code="message.button.startSpacing"></spring:message></label></ms:btn>
             <ms:btn url="/sysUser/subDisable.html"><label class="btn btn-primary btn-sm" onclick="batchChangeStatus(0)"><spring:message code="message.button.stopSpacing"></spring:message></label></ms:btn>
        </div>
		<div class="modal fade" id="changePasswordDialog" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header bg-primary">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
						<h5 class="modal-title"><spring:message code="message.lable.resetPWD"></spring:message></h5>
					</div>
					<div class="modal-body">
						<div class="form-group form-group-xs">
							<label for="password" class="control-label"><spring:message code="message.lable.newPWD"></spring:message>：</label>
							<input class="form-control" type="password" id="password" maxlength="127" />
						</div>
						<div class="form-group form-group-xs">
							<label for="passwordRepeat" class="control-label"><spring:message code="message.lable.confirmPWD"></spring:message>：</label>
							<input class="form-control" type="password" id="passwordRepeat" maxlength="20" />
						</div>
						   <div class="form-group form-group-xs">
					        <label for="newpassword" class="col-sm-2 text-right"><i class="fa fa-exclamation-circle fa-lg" style="color:#dd4b39;"></i>&nbsp;<span style="color:#dd4b39;font-weight:600"><spring:message code="message.lable.tiShi" />：</span></label>					        
						    <div class="col-sm-6.5 text-left" style="color:#dd4b39">
						         <spring:message code="message.lable.PWDhint" />
						    </div>
				         </div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-primary btn-sm reSetPsr" onclick="submitPassword();"><spring:message code="message.button.okSpacing"></spring:message></button>
						<button type="button" class="btn btn-danger btn-sm" id="closeChangePasswordDialog" data-dismiss="modal"><spring:message code="message.button.closeSpacing"></spring:message></button>
					</div>
				</div>
			</div>
		</div>
		<!-- 新增/编辑子账户 -->
         <form id="form" class="form-horizontal" action="" method="post">
         <input type="hidden" id="editiId" name="id" />
	        <div class="modal fade" id="userModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<div class="modal-header bg-primary">
							<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
							 <h5 class="modal-title"></h5>
						</div>
						<div class="modal-body">
							<div class="form-group form-group-xs">
								 <label for="name" class="col-sm-2 text-right"><span class="required">*</span><spring:message code="message.lable.usernameBlank"></spring:message>：</label>
	                          	 <div class="col-sm-3 text-left">
	                            	<input class="form-control" id="name" name="name"  placeholder="<spring:message code="message.lable.usernameBlank"></spring:message>" type="text" maxlength="50">
	                           	 </div>
	                           	  <label for="roleId" class="col-sm-3 text-right"><span class="required">*</span><spring:message code="message.lable.userjueseBlank"></spring:message>：</label>
	                        <div class="col-sm-3 text-left">
	                            <select class="form-control" id="roleId" name="roleId">
	                            	<c:if test="${ roleList != null }">
	                            		<option value=""><spring:message code="message.select.option"/></option>
	                            		<c:forEach items="${ roleList }" var="role">
	                            			<option value="${ role.id }">${ role.name }</option>
	                            		</c:forEach>
	                            	</c:if>
	                            </select>
							</div>
							</div>
	                    <div class="form-group form-group-xs">
	                     <label for="email" class="col-sm-2 text-right"><spring:message code="message.lable.useremailBlank"></spring:message>：</label>
	                        <div class="col-sm-3 text-left">
	                            <input class="form-control" id="email" name="email" value="${user.email}" placeholder="<spring:message code="message.lable.useremailBlank"></spring:message>" type="text" maxlength="25">
	                        </div>
	                        <label for="phone" class="col-sm-3 text-right"><spring:message code="message.lable.phoneBlank" /><spring:message code="message.yanZheng.maoHao"/></label>
	                        <div class="col-sm-3 text-left">
	                            <input class="form-control" id="phone" name="phone" value="${user.phone}" placeholder="<spring:message code="message.lable.phoneBlank"></spring:message>" type="text" maxlength="25">
	                        </div>
	                    </div>
	                    <div class="form-group form-group-xs">
	                        <label for="remark" class="col-sm-2 control-label"><spring:message code="message.lable.remarkBlank"></spring:message><spring:message code="message.yanZheng.maoHao"/></label>
	                        <div class="col-sm-9">
	                            <textarea class="form-control" id="remark" name="remark" rows="3" placeholder="<spring:message code="message.lable.remarkBlank"></spring:message>" maxlength="500">${user.remark}</textarea>
	                        </div>
	                    </div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-primary btn-sm" onclick="subSaveUser();"><spring:message code="message.button.saveSpacing"></spring:message></button>
					<button type="button" class="btn btn-danger btn-sm" id="close" data-dismiss="modal"><spring:message code="message.button.closeSpacing"></spring:message></button>
				</div>
			</div>
			</div>   
		</div>  
	</form>
    </section>
    <%@ include file="/WEB-INF/component/commonJS.jsp" %>
    <script type="text/javascript">
	 $(function(){
		 $("#searchName").focus();//加载页面光标在第一个查询框内
		 
		   $('.form-inline :input').bind('keydown', function(event) {if (event.keyCode == "13") {search();}}).eq(0).focus();
		   $("form#form :input").change(function(){
	    		$("form#form").data("changed",true);
	       })
	 })
    	var id = "";
	 	var userName ="";
    	function changePassword(_id,username,name) {
    		id = _id || "";
    		$("#password").val("");
    		$("#passwordRepeat").val("");
    		$("#changePasswordDialog").find(".modal-title").html(username+" - "+name);
    		$('#changePasswordDialog').modal({
                keyboard: true
            });
    		userName=username;
    	}
    	
    	function changeStatus(id,username,flag) {
        	var statusName = "<spring:message code='message.button.start' />";
        	if (flag == 0){
        		statusName = "<spring:message code='message.button.stop' />";
        	}
      	  $.HN.message.confirm("<spring:message code='message.button.confirm' />"+statusName+"<spring:message code='message.HN.alert.yiXiaZhangHao' /><spring:message code="message.yanZheng.wenHao"/><br/>"+username, '', '').on(function (e) {
                if (e) {
                	$.ajax({
                        url: "${ctx}/sysUser/changeStatus.html",//action地址
                        data: { status:flag,id:id},//传值
                        type: "post",//执行方式get or post 默认以post方式执行
                        dataType:"json",
                        success: function (result) {//执行成功后 提示
                            if (result.success){
                            	top.$.HN.message.alert("<spring:message code='message.HN.alert.chengGong' />"+statusName+username+"<spring:message code="message.yanZheng.ganTanHao"/>","", "success");
                               search( $("#gridlist").getGridParam("page"));
                           } else {
                        	   top.$.HN.message.alert("<spring:message code='message.HN.alert.fail' /><spring:message code="message.yanZheng.ganTanHao"/>","","error");
                           } 
                        }
                    });
                }
            });
    	}
    	function batchChangeStatus(flag) {
	   	  var statusName = "<spring:message code='message.button.start' />";
	   	  var url="${ctx}/sysUser/subEnable.html";
	      if (flag == 0){
	       		statusName = "<spring:message code='message.button.stop' />";
	       		url="${ctx}/sysUser/subDisable.html";
	      }
	       	//获取选中的ID及对应的名字（参数:jqgridId,名字列名，状态列名，当前操作即列表中显示的值），返回infos[0]是ID串，infos[1]是名字串
	      var infos = batchSwitchStatus("gridlist","username","statusName",statusName,"<spring:message code='message.lable.userzhanghao'/>");
	      if ( !(infos instanceof Array)){
	       		return;
	      }
      	  $.HN.message.confirm('<spring:message code='message.button.confirm' />'+statusName+'<spring:message code='message.HN.alert.yiXiaZhangHao' /><br/>'+infos[1].replace(/\,/g,"<br/>"), '', '').on(function (e) {
                if (e) {
                	$.ajax({
                        url: url,//action地址
                        data: { state:flag,param:infos[0] },//传值
                        type: "post",//执行方式get or post 默认以post方式执行
                        dataType:"json",
                        success: function (result) {//执行成功后 提示
                            if (result.success){
                            	top.$.HN.message.alert("<spring:message code='message.HN.alert.chengGongCaoZuo' />"+infos[0].split(",").length+"<spring:message code='message.HN.alert.tiaoShuJu' /><spring:message code="message.yanZheng.ganTanHao"/>","", "success");
                               search( $("#gridlist").getGridParam("page"));
                           } else {
                        	   top.$.HN.message.alert("<spring:message code='message.HN.alert.fail' /><spring:message code="message.yanZheng.ganTanHao"/>","", "error");
                           } 
                        }
                    });
                }
            });
    	}
    	function search(page) {
    		var username = $.trim($("#subUsername").val());
    		var name = $.trim($("#searchName").val());
    		var status = $.trim($("#myStatus").val());
    		$("#gridlist").jqGrid('setGridParam',{  
    	        datatype:'json',
    	        postData:{"name":name,"status":status,"username":username},
    	        page : (page || 1)
    	    }).trigger("reloadGrid"); //重新载入  
    	}
    	
    	function submitPassword() {
			var password = $.trim($("#password").val());
			var passwordRepeat = $.trim($("#passwordRepeat").val());
			//var parn = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.\/]).{6,12}$/;
			var parn =new RegExp("^[0-9]*$");
		     if (password == null || password == "") {
		         $.HN.message.alert("<spring:message code='message.HN.noPWD'/><spring:message code="message.yanZheng.ganTanHao"/>", "", "warn");
		         return false;
		     } else if (!(parn.test(password))) {
		    	 $.HN.message.alert("<spring:message code='message.lable.PWDhint'/>", "<spring:message code='message.HN.alert.type'/>", "warn");
		         return false;
		     } else if (password.length != 6) {
		         $.HN.message.alert("<spring:message code='message.HN.PWDlengthDengYu6'/><spring:message code="message.yanZheng.ganTanHao"/>", "", "warn");
		         return false;
		     }
		     if (passwordRepeat == null || passwordRepeat == "") {
		         $.HN.message.alert("<spring:message code='message.HN.noConfirmPWD'/><spring:message code="message.yanZheng.ganTanHao"/>", "", "warn");
		         return false;
		     } else if (passwordRepeat != password ) {
		         $.HN.message.alert("<spring:message code='message.HN.notSamePWD'/>", "", "warn");
		         return false;
		     }
		     
	      	  $.HN.message.confirm("<spring:message code='message.lable.queDingWei'/>"+userName+"<spring:message code='message.lable.zhangHaoChongZhiMiMa'/>", '', '').on(function (e) {
	              if (e) {
	            		$.post("${ctx}/sysUser/changePassword.html", {
	            			"id" : (id || ""),
	            			"password" : password
	            		}, function(result) {
	            			if (result.success) {
	            				$("#closeChangePasswordDialog").click();
	            				$.HN.message.alert("<spring:message code='message.HN.alert.success'/><spring:message code="message.yanZheng.ganTanHao"/>", "<spring:message code='message.HN.alert.type'/>", "success");
	            			} else {
	            				$.HN.message.alert("<spring:message code='message.HN.alert.fail'/><spring:message code="message.yanZheng.ganTanHao"/>", "<spring:message code='message.HN.alert.type'/>", "error");
	            			}
	            		}, "json").error(function(err) {
	            			top.window.document.location = "${ctx}/login.html"; 
	            		});
	    		}
	       	  });
       }
    
        $(function () {
            $("#gridlist").jqGrid({
                url: "${ctx}/sysUser/getSubUserList.html",
                mtype: "post",
                datatype: "json",
                autowidth: true,
                height: 280,
                colNames: [
                    '<spring:message code='message.jqGrid.cz'/>',
                    '<spring:message code='message.lable.userzhanghao'/>',
					'<spring:message code='message.lable.username'/>', 
					'<spring:message code='message.lable.userjuese'/>', 
					'<spring:message code='message.lable.useremail'/>',
					'<spring:message code='message.lable.phone'/>',
					'<spring:message code='message.lable.status'/>',
					"statusName"
                ],
                colModel: [
                   { name: 'operate', width: 8, align:"center", sortable: false,
                 	formatter : function(val, opts, rowdata) {
                 		var	str ="";
                 		var email= rowdata.email!=null?rowdata.email:"";
                 		var phone = rowdata.phone!=null?rowdata.phone:"";
                 		var remark = rowdata.remark!=null?rowdata.remark:"";
                 		str += "<ms:btn url='/sysUser/subEditUser.html'><a href=\"javascript:showDiv('edit','"+rowdata.id+"','"+rowdata.name+"','"+rowdata.role.id+"','"+email+"','"+phone+"','"+remark+"');\" style='background:url(${ctx}/lib/img/icon/icon.png) no-repeat 0px 0px' class='opIcon' title='<spring:message code='message.button.edit'/>'></a></ms:btn>";
		            	str += "<ms:btn url='/sysUser/changePassword.html'><a href='javascript:changePassword(\""+rowdata.id+"\",\""+rowdata.username+"\",\""+rowdata.name+"\");' style='background:url(${ctx}/lib/img/icon/icon.png) no-repeat -20px 0px' class='opIcon' title='<spring:message code='message.lable.resetPWD'/>'></a></ms:btn>";
		            	str += "<ms:btn url='/sysPrivilege/subUserPrivilege.html'><a href='javascript:subUserPrivilege(\""+rowdata.id+"\",\""+rowdata.name+"\");' style='background:url(${ctx}/lib/img/icon/icon.png) no-repeat -60px -80px' class='opIcon' title='<spring:message code='message.lable.role' />'></a></ms:btn>";
		            	return str;
                    }
                   },      
					{ name: 'username', width: 8, align:"center", sortable: false},
                    { name: 'name', width: 10, align:"left", sortable: false},
                    { name: 'role.name', width: 10, align:"center", sortable: false },
                    { name: 'email', width: 9, align: 'left', sortable: false},
                    { name: 'phone', width: 10, align: 'left', sortable: false},
                    { name: 'status', width: 5, align: 'center', sortable: false,
                    	formatter : function(val,opts,row){
	                    	if(val==1){
	                    		return "<spring:message code="message.button.start"></spring:message>";
	                    	}else if(val==0){
	                    		return "<span class='red'><spring:message code="message.button.stop"></spring:message></span>";
	                    	}
	                    }
                    },
                    { name: 'statusName', width: 0,hidden:true ,align: 'left', sortable: false}
                ],
                rowNum: 20,
                rowList: [10, 20, 30],
                rownumbers: true,
                pager: "#gridpage",
                multiselect: true, 
                viewrecords: true,
                caption: "<spring:message code='message.lable.ziyinghuLieBiao'/>",
                gridComplete:function(){
                    autoRNWidth("gridlist");
                    selectByOneData("gridlist");
                },
                jsonReader: {
                    id: "id"
                }
            });
            $("#gridlist").jqGrid('navGrid', '#gridpage', { add: false, edit: false, del: false, search: false, refresh: false });
            $(window).trigger("resize");
            
        });
        
        function showDiv(opType,id,name,roleId,email,phone,remark){
        	$("#form")[0].reset();
        	$("#roleId").prop("selectedIndex",0);
        	if("add"==opType){//新增
        		$("#form").attr("action","subSaveUser.html");
        		$("#editiId").val("");
        		$("h5.modal-title").html("<spring:message code='message.lable.ziyonghu' /><spring:message code='message.button.add' />");
        	}else if("edit"==opType){//编辑
        		$("#form").attr("action","subEditUser.html");
        		$("h5.modal-title").html("<spring:message code='message.lable.ziyonghu' /><spring:message code='message.button.edit' />");
        		  	$("#editiId").val(id);
        			$("#name").val(name);
					$("#email").val(email);
	 				$("#phone").val(phone);
	 				$("#remark").val(remark);
	 				$("#roleId").find("option").each(function(){
            			if($.trim($(this).val()) == $.trim(roleId)){
                			$(this).attr("selected",true);return;
                		}
            	 	}); 
	 		$("form#form").data("changed",false);
        	}
        	$('#userModal').modal({
                keyboard: true
            })
        }
        function subSaveUser(){
	   		if (!validate()) {
	   			return;
	   		}
       	  $.HN.message.confirm("<spring:message code='message.HN.alert.OkSaveYESorNO'/>", '', '').on(function (e) {
              if (e) {
          		$("#form").ajaxSubmit({
        			type : "post",
        			dataType : "json",
        			contentType: "application/x-www-form-urlencoded; charset=utf-8", 
        			timeout: 10000,
        			success : function(result, statusText) {
        				if (result.success) {
        					    $('#userModal').modal('hide');
        					    var un=result.conditions.username;
        					    var psr=result.conditions.password;
        					    if(un!=null && un!="" && psr!=null && psr!=""){
        					    	toSubAccount(un,psr,result.conditions.role);
        					    }
        					    search($("#gridlist").getGridParam("page"));
        						top.$.HN.message.alert("<spring:message code='message.HN.alert.success'/><spring:message code="message.yanZheng.ganTanHao"/>", "<spring:message code='message.HN.alert.type'/>", "success");
        						
        				} else {
        					$.HN.message.alert(result.msg || "", "<spring:message code='message.HN.alert.type'/>", "error");
        				}
        			}
        		});
    		}
       	  });
        }
        
	    function toSubAccount(name,psr,roleName){
			var url = encodeURI(encodeURI("${ctx}/sysUser/toSubAccount.html?name="+name+"&psr="+psr+"&roleName="+roleName));
	    	$.HN.dialog.open({
	             id:id,
	             title:"<spring:message code="message.lable.ziyonghu"/><spring:message code="message.button.add"/>",
	             url: url,
	             width:"320px",
	             height:"185px",
	             closefunc:function(){
	            	 search();
	             }
	         });
    }
        function validate(){
	        if(!$("form#form").data("changed")){
				top.$.HN.message.alert("<spring:message code='message.lable.noModify'/>", "", "warn");
				return false;  		
	    	}
    	
        	var name = $.trim($("#name").val());
    		if (name == null || name == "") {
    			top.$.HN.message.alert("<spring:message code='message.lable.text'/><spring:message code='message.HN.alert.input'/><spring:message code='message.lable.username'/><spring:message code="message.yanZheng.ganTanHao"/>", "<spring:message code='message.HN.alert.type'/>", "warn");
    			$("#name").focus();
    			return false;
    		}
    		
    		var roleId = $("#roleId")[0] ;
    		if(roleId.selectedIndex ==-1 || roleId.selectedIndex ==0){ //-1表一个都没选 ，0表选了第一个
    			top.$.HN.message.alert("<spring:message code='message.select.option'/><spring:message code='message.lable.userjuese'/><spring:message code="message.yanZheng.ganTanHao"/>", "", "warn");
    			return false;
    		}
    		
    		var email = $.trim($("#email").val());
    		if (email != null || email != "") {
    	 		if (email.replace(/(^s*)|(s*$)/g, "").length !=0) {
       			var a =/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
       			if(!a.test(email)){
       				top.$.HN.message.alert("<spring:message code='message.lable.useremail'/><spring:message code='message.HN.alert.gsbzq'/><spring:message code="message.yanZheng.ganTanHao"/>", "<spring:message code='message.HN.alert.type'/>", "warn");
   		        	$("#email").focus();
   	    			return false;
	   		   		 }
	       		}
    		}
    		var phone = $.trim($("#phone").val());
    		if (phone != null || phone != "") {
    			if (phone.replace(/(^s*)|(s*$)/g, "").length !=0) {
        			var b=/((15)\d{9})|((13)\d{9})|((18)\d{9})|(0[1-9]{2,3}\-?[1-9]{6,7})/i;  
        			if(!b.test(phone)){
        				top.$.HN.message.alert("<spring:message code='message.lable.phone'/><spring:message code='message.HN.alert.gsbzq'/>", "<spring:message code='message.HN.alert.type'/>", "warn");
        		        	$("#phone").focus();
        	    			return false;
        		    }
        		}
    		}
    		return true;
        }
        function subUserPrivilege(id,name){
        	$.HN.dialog.open({
                 id:id,
                 title:name,
                 url:"${ctx}/sysPrivilege/subUserPrivilege.html?userId="+id,
                 width:"800px",
                 height:"550px",
                 closefunc:function(){
                	 search($("#gridlist").getGridParam("page"));
                 }
             });
    }
        </script>
</body>
</html>